<template>
    <div class="app-container">
        <!-- 移动端骨架屏 -->
        <mobile-skeleton 
            v-if="isMobile && loading" 
            :showHeader="true"
            :showForm="true"
            :formFields="4"
            :showButton="true"
            :showPagination="false"
        />
        
        <div v-else>
            <!-- 桌面端头部 -->
            <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start" v-if="!isMobile">
                <el-col :span="1">
                    <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer; margin-left: 10px" @click="handleBack" />
                </el-col>
                <el-col :span="23">
                    <h3 :style="{ color: theme }">岗位配置</h3>
                </el-col>
            </el-row>
            
            <!-- 移动端头部 -->
            <div class="mobile-header" v-if="isMobile">
                <div class="back-btn" @click="handleBack">
                    <img :src="backImg" />
                </div>
                <div class="page-title">岗位配置</div>
                <div class="placeholder"></div>
            </div>
            
            <el-form ref="form" :model="form" :rules="rules" 
                    :label-position="isMobile ? 'top' : 'left'" 
                    :label-width="isMobile ? '0px' : '120px'"
                    :class="{'mobile-form': isMobile}">
                <el-card style="padding-top: 20px" :class="{'mobile-card': isMobile}">
                    <el-form-item label="证书名称" prop="name" placeholder="请输入证书名称">
                        <el-input v-model="form.name" />
                    </el-form-item>
                    <el-form-item label="证书级别" prop="level">
                        <el-input v-model="form.level" placeholder="请输入证书等级">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="证书描述" prop="desc">
                        <el-input type="textarea" :rows="4" placeholder="请输入证书描述" v-model="form.desc">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="关联培训" prop="course">
                        <el-select v-model="form.course" multiple placeholder="请选择">
                            <el-option v-for="item in courseOptions" :key="item.id" :label="item.label" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关联考试" prop="course">
                        <el-select v-model="form.course" multiple placeholder="请选择">
                            <el-option v-for="item in courseOptions" :key="item.id" :label="item.label" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="state" label="状态">
                        <el-radio-group v-model="form.state">
                            <el-radio :label="false">不启用</el-radio>
                            <el-radio :label="true">启用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button 
                            :loading="loading" 
                            type="primary" 
                            @click="submitForm" 
                            :style="{
                                backgroundColor: theme,
                                borderColor: theme,
                                fontWeight: 'bold',
                            }"
                            :class="{'mobile-button': isMobile}"
                        >
                            保存
                        </el-button>
                    </el-form-item>
                </el-card>
            </el-form>
        </div>
    </div>
</template>

<script>
import backImg from "@/assets/images/back.png";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { treeselectDeptUser } from "@/api/vadmin/permission/dept";
import { categoryTree } from "@/api/vadmin/course/course";
import {
    postCertificationDetail,
    certificationPass,
    UpdatePostCertification,
    AddPostCertification,
} from "@/api/vadmin/certification/certification";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
    name: "NewPost",
    components: { 
        MobileSkeleton 
    },
    data() {
        return {
            form: { name: "" },
            courseOptions: [], //所有课程
            userOptions: [],
            //data value filterMethod为elment穿梭框使用
            defaultProps: {
                children: "children",
                label: "label",
            },
            userDefaultProps: {
                children: "users",
                label: "name",
            },
            loading: false,
            backImg: backImg,
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 表单校验
            rules: {
                name: [
                    { required: true, message: "认证名称不能为空", trigger: "blur" },
                ],
                state: [
                    { required: true, message: "是否通过不能为空", trigger: "blur" },
                ],
            },
            screenWidth: document.body.clientWidth,
            mediaQueryList: null,
            isMobile: false,
        };
    },

    computed: {
        ...mapState(["settings"]),
        variables() {
            return variables;
        },
        theme() {
            return this.$store.state.settings.theme;
        },
    },
    created() {
        if (this.$route.params.id !== undefined && this.$route.params.id) {
            const id = this.$route.params.id;
            this.getList(id);
        }

        this.getBasicData();
        
        // 监听屏幕宽度变化
        window.addEventListener('resize', this.handleResize);
    },
    
    mounted() {
        // 使用媒体查询API直接监听视口变化
        this.mediaQueryList = window.matchMedia('(max-width: 767px)');
        
        // 初始化isMobile状态
        this.isMobile = this.mediaQueryList.matches;
        
        // 为媒体查询添加监听器
        const handleMediaChange = (e) => {
            this.isMobile = e.matches;
            
            // 强制组件重新渲染
            this.$forceUpdate();
        };
        
        // 使用适当的API添加监听器
        if (this.mediaQueryList.addEventListener) {
            this.mediaQueryList.addEventListener('change', handleMediaChange);
        } else {
            // 旧版浏览器支持
            this.mediaQueryList.addListener(handleMediaChange);
        }
        
        // 存储监听器以便后续移除
        this.mediaChangeHandler = handleMediaChange;
    },
    
    beforeDestroy() {
        // 移除监听器
        window.removeEventListener('resize', this.handleResize);
        
        // 移除媒体查询监听器
        if (this.mediaQueryList) {
            if (this.mediaQueryList.removeEventListener) {
                this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
            } else {
                // 旧版浏览器支持
                this.mediaQueryList.removeListener(this.mediaChangeHandler);
            }
        }
    },

    methods: {
        // 处理屏幕大小变化
        handleResize() {
            this.screenWidth = document.body.clientWidth;
        },
        
        handleBack() {
            this.$router.push({ name: "Postcertification" });
        },
        getList(id) {
            this.loading = true;
            postCertificationDetail(id).then((res) => {
                // console.log("详情", res);
                this.form = res;
                this.form.course = res.course.map((item) => {
                    return item.id;
                });
                this.loading = false;
            }).catch(() => {
                this.loading = false;
            });
        },

        getBasicData() {
            categoryTree({ page_size: 1000, page: 1 }).then((response) => {

                this.courseOptions = response;
            });
            // 获取所有人员
            treeselectDeptUser({ page_size: 1000, page: 1 }).then((response) => {
                this.userOptions = this.handleUsersTree(response.results, "id");
            });
        },
        /** 提交按钮 */
        submitForm: function() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.form.course = this.$refs.tree.getCheckedKeys();
                    const cloneData = JSON.parse(JSON.stringify(this.form));

                    if (this.form.id != undefined) {
                        UpdatePostCertification(cloneData).then((response) => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                        });
                    } else {
                       
                        AddPostCertification(cloneData).then((response) => {
                            this.msgSuccess("新增成功");
                            this.open = false;
                            this.form = {};
                        });
                    }
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.app-container {
    background-color: transparent;
    padding: 0;
}

.pre-exam div {
    line-height: 42px;
    color: #555555;
}

.post-tree {
    border: 1px solid #dcdfe6;
}

.el-tree {
    z-index: 9999
}

/* 移动端样式 */
.mobile-header {
    position: sticky;
    top: 0;
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    padding: 0 15px;
    margin-bottom: 15px;
    border-radius: 8px;
    
    .back-btn {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        img {
            width: 24px;
            height: 24px;
        }
    }
    
    .page-title {
        font-size: 17px;
        font-weight: 500;
    }
    
    .placeholder {
        width: 40px;
    }
}

.mobile-form {
    .el-form-item__label {
        padding-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
    }
    
    .el-select, .el-input {
        width: 100%;
    }
    
    .el-card {
        border-radius: 8px;
    }
}

.mobile-card {
    /deep/ .el-card__body {
        padding: 15px !important;
    }
}

.mobile-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    border-radius: 8px;
    margin-top: 10px;
}
</style>